<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="2">
        <span style="color: blue">{{ tplItem.名称 }}</span>
      </el-col>
      <el-col :span="3">
        <el-switch
          @change="filterTable"
          v-model="hideBasicObj"
          :active-value="true"
          :inactive-value="false"
          active-text=""
          inactive-text="隐藏基础项目"
        >
        </el-switch>
      </el-col>
      <el-col :span="3">
        <el-switch
          @change="filterTable"
          v-model="隐藏备选项目"
          active-text=""
          inactive-text="隐藏备选项目"
        >
        </el-switch>
      </el-col>
      <el-col :span="3">
        <el-switch
          v-model="tplItem.是否审核"
          active-text="审核"
          inactive-text="取消审核"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-col>

      <el-col :span="2">
        <el-link type="primary" @click="查看文件('路径表单')">路径表单</el-link>
      </el-col>
      <el-col :span="2">
        <el-link type="primary" @click="查看文件('路径方案')">路径方案</el-link>
      </el-col>
      <!-- <el-col :span="1">
        <el-button
          type="success"
          @click="查看文件('路径方案')"
          style="margin-left: 5px"
          round
          >路径表单</el-button
        >
      </el-col> -->
      <el-col :span="4">
        <el-input
          v-model="s"
          @keyup.enter.native="filterTable"
          style="margin-top: -5px"
          placeholder="类别、项目名称  回车"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-button
          round
          type="primary"
          @click="saveTpl"
          :loading="saveLoading"
          style="margin-top: -10px"
          >保存
        </el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-table
        border
        :data="tplDataLs"
        :summary-method="summary"
        :loading="tplLoading"
        :show-summary="true"
        style="width: 100%"
        max-height="600"
        :row-style="rowStyle"
      >
        <el-table-column fixed type="index" width="50"> </el-table-column>
        <el-table-column fixed prop="类别" label="类别" width="150">
        </el-table-column>
        <el-table-column fixed prop="项目名称" label="项目名称">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content" v-html="item_content(scope.row)"></div>
              <el-select
                @focus="项目名称_focus(scope.row, $event)"
                @change="项目名称_change(scope.row, scope.row.项目名称)"
                v-model="scope.row.项目名称"
                filterable
                remote
                reserve-keyword
                style="width: 100%"
                placeholder="请输入关键词"
                :remote-method="远程搜索项目"
                :loading="项目Loading"
                :disabled="tplItem.是否审核"
              >
                <el-option
                  v-for="item in 匹配项目s"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                >
                  <div class="drgItem">
                    <span>{{ item.label }}</span>
                    <span>{{ item.value.规格 }}</span>
                    <span style="color: #8492a6; font-size: 13px">{{
                      item.value.生产厂家
                    }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="单价" label="单价" width="100">
          <template slot-scope="scope">
            <template v-if="!tplItem.是否审核">
              <el-input
                v-if="scope.row.缺省"
                v-model="scope.row.单价"
                placeholder="单价"
              ></el-input>
              <span v-else>{{ scope.row.单价 }}</span>
            </template>

            <span v-else>{{ scope.row.单价 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="数量" label="数量" width="100">
          <template slot-scope="scope">
            <template v-if="!tplItem.是否审核">
              <el-input
                v-if="scope.row.缺省"
                v-model="scope.row.数量"
                placeholder="数量"
              ></el-input>
              <span v-else>{{ scope.row.数量 }}</span>
            </template>
            <span v-else>{{ scope.row.数量 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="金额"
          :formatter="计算费用fmt"
          label="金额"
          width="80"
        >
        </el-table-column>
        <el-table-column prop="项目属性" label="项目属性" width="120">
        </el-table-column>
        <el-table-column prop="选择属性" :label="'选择属性'" width="120">
          <template slot-scope="scope">
            <template v-if="!tplItem.是否审核">
              <el-select v-model="scope.row.选择属性" placeholder="请选择">
                <el-option
                  v-for="item in 选择属性s"
                  :key="item.value"
                  :label="item.lable"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </template>

            <span v-else>{{ scope.row.选择属性 }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="缺省" :label="'缺省'" width="80">
          <template slot-scope="scope">
            <el-checkbox
              :disabled="tplItem.是否审核"
              @click.native="缺省_click(scope.row)"
              v-model="scope.row.缺省"
            ></el-checkbox>
          </template>
        </el-table-column>

        <el-table-column prop="组号" label="组号" width="100">
          <template slot-scope="scope">
            <template v-if="!tplItem.是否审核">
              <el-select v-model="scope.row.组号" placeholder="请选择">
                <el-option
                  v-for="item in [
                    {
                      label: '',
                    },
                    {
                      label: 'I',
                    },
                    {
                      label: 'II',
                    },
                    {
                      label: 'III',
                    },
                    {
                      label: 'IV',
                    },
                    {
                      label: 'V',
                    },
                  ]"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </template>
            <span v-else>{{ scope.row.组号 }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="限制" label="限制" width="80">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.限制说明"
              Left="提示文字"
              placement="top-start"
            >
              <span style="color: red">{{ scope.row.限制 }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          :formatter="费用结构情况fmt"
          prop="模板费用"
          :label="'模板费用'"
          width="100"
        >
        </el-table-column>
        <el-table-column
          :formatter="模板费用占比fmt"
          prop="模板费用占比"
          :label="'模板费用\n占比%'"
          width="80"
        >
        </el-table-column>

        <el-table-column fixed="right" label="" width="100">
          <template slot-scope="scope">
            <el-dropdown>
              <span class="el-dropdown-link" style="color: blue">
                操作<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  @click.native.prevent="
                    dropdown_itemClick(scope.row, scope.$index, 'insertUP')
                  "
                  icon="el-icon-plus"
                  >添加（上）</el-dropdown-item
                >
                <el-dropdown-item
                  @click.native.prevent="
                    dropdown_itemClick(scope.row, scope.$index, 'insertDown')
                  "
                  icon="el-icon-plus"
                  >添加（下）</el-dropdown-item
                >

                <el-dropdown-item
                  @click.native.prevent="
                    dropdownInsertType_itemClick(
                      scope.row,
                      scope.$index,
                      'insertTypeUP'
                    )
                  "
                  icon="el-icon-plus"
                  >插入类别（上）</el-dropdown-item
                >
                <el-dropdown-item
                  @click.native.prevent="
                    dropdownInsertType_itemClick(
                      scope.row,
                      scope.$index,
                      'insertTypeDown'
                    )
                  "
                  icon="el-icon-plus"
                  >插入类别（下）</el-dropdown-item
                >

                <el-dropdown-item
                  @click.native.prevent="
                    dropdown_itemClick(scope.row, scope.$index, 'remove')
                  "
                  icon="el-icon-close"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-descriptions title="模板类型">
        <el-descriptions-item label="路径版本">
          {{ tplItem.路径版本 }}
        </el-descriptions-item>
        <el-descriptions-item label="当前分组">
          <el-select
            style="width: 180px"
            @change="tplitem_change"
            v-model="tplItem.分组编码"
            placeholder="请选择"
          >
            <el-option
              v-for="item in drgNameLs"
              :key="item.分组编码"
              :label="item.分组编码 + '-' + item.分组名称"
              :value="item.分组编码"
            >
            </el-option>
          </el-select>
        </el-descriptions-item>

        <!-- <el-descriptions-item label="时间段内当前模版的本院数据">
                    {{ 模板病例数 }}
                </el-descriptions-item> -->
      </el-descriptions>
    </el-row>

    <el-row>
      <el-descriptions title="大数据标杆">
        <el-descriptions-item label="医保付费标杆">
          {{ 大数据标杆.平均费用 }}
        </el-descriptions-item>
        <el-descriptions-item label="药品费">
          {{ 大数据标杆.平均药品费 }}
        </el-descriptions-item>
        <el-descriptions-item label="检验费">
          {{ 大数据标杆.平均检验费 }}
        </el-descriptions-item>
        <el-descriptions-item label="检查费">
          {{ 大数据标杆.平均检查费 }}
        </el-descriptions-item>
        <el-descriptions-item label="治疗费">
          {{ 大数据标杆.平均治疗费 }}
        </el-descriptions-item>
        <el-descriptions-item label="手术费">
          {{ 大数据标杆.平均手术费 }}
        </el-descriptions-item>
        <el-descriptions-item label="耗材费">
          {{ 大数据标杆.平均耗材费 }}
        </el-descriptions-item>
        <el-descriptions-item label="医保床日标杆">
          {{ 历史标杆.平均床日 }}
        </el-descriptions-item>
      </el-descriptions>
    </el-row>

    <el-row>
      <el-descriptions title="本院历史标杆">
        <el-descriptions-item label="本院次均费用">
          {{ 历史标杆.平均费用 }}
        </el-descriptions-item>
        <el-descriptions-item
          :label="是否中医性质 ? '（西药）成药费' : '药品费'"
        >
          {{ 历史标杆.平均药品费 }}
        </el-descriptions-item>
        <el-descriptions-item label="检验费">
          {{ 历史标杆.平均检验费 }}
        </el-descriptions-item>
        <el-descriptions-item label="检查费">
          {{ 历史标杆.平均检查费 }}
        </el-descriptions-item>
        <el-descriptions-item label="治疗费">
          {{ 历史标杆.平均治疗费 }}
        </el-descriptions-item>
        <el-descriptions-item label="手术费">
          {{ 历史标杆.平均手术费 }}
        </el-descriptions-item>
        <el-descriptions-item label="耗材费">
          {{ 历史标杆.平均耗材费 }}
        </el-descriptions-item>
        <el-descriptions-item label="本院平均床日">
          {{ 大数据标杆.平均床日 }}
        </el-descriptions-item>
        <el-descriptions-item v-if="是否中医性质" label="草药费">
          {{ 历史标杆.平均草药费 }}
        </el-descriptions-item>
      </el-descriptions>
    </el-row>

    <el-row>
      <el-dialog
        :title="uploadTitle"
        :visible.sync="uploadDialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <ul class="el-upload-list el-upload-list--text">
          <li
            v-for="f in 文件s"
            v-bind:key="f.name"
            class="el-upload-list__item is-ready"
          >
            <a
              class="el-upload-list__item-name"
              target="_blank"
              :href="downLoadUrl + '/' + f.url"
              ><i class="el-icon-document"></i>{{ f.name }}</a
            >
          </li>
        </ul>
      </el-dialog>
    </el-row>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import {
  tplDetail,
  saveTpl,
  drgNames,
  drgInfo,
  cnHops,
  saveTplDrg,
  drgweightbyid,
} from "@/api/PathTemplate";
import { GetTplById } from "@/api/pathway";
import { Format } from "@/utils/Utils";
import { autoName } from "@/api/commonApi";
import { LsFiles, DestoryFile } from "@/api/commonApi";
import { UserModule } from "@/store/modules/user";
@Component({
  name: "tpledit",
})
export default class extends Vue {
  private tplid: string = "";

  public 项目Loading: boolean = false;

  public 匹配项目s: Array<any> = [];

  private uploadDialogVisible: boolean = false;
  private uploadTitle: string = "";
  private 文件s: Array<any> = [];
  private downLoadUrl = `${(<any>window).MyConf.APISERVICE}/files/`;

  private rowStyle(p: any) {
    let row = p.row;
    if (row.特征对比结果) {
      return { color: "red" };
    }
    return {};
  }
  private async 查看文件(t: string) {
    let ts = [];
    this.uploadDialogVisible = true;
    this.uploadTitle = t;

    const { data } = await LsFiles({ tpl: `${this.tplid}-${t}` });
    this.文件s = data;
  }

  private editRow: any = {};
  public 缺省_click(row: any) {
    if (row.缺省) {
      row.数量 = null;
    }
  }
  public 项目名称_focus(row: any, $event: any) {
    this.editRow = row;
  }
  public item_content(row: any) {
    return `${row.项目名称}<br/> ${row.产地 || ""}&nbsp;&nbsp;${
      row.规格 || ""
    }<br/>${row.适用范围}`;
  }

  public 项目名称_change(row: any, value: any) {
    row.项目id = value.项目id;
    row.项目名称 = value.名称;
    row.项目属性 = "";

    row.产地 = value.生产厂家;
    row.规格 = value.规格;
    if (value.售价) {
      row.单价 = value.售价;
    }

    if (value.属性 == 1) row.项目属性 = "基础项目";
    if (value.属性 == 2) row.项目属性 = "不判断";

    //项目重复检查
    setTimeout(() => {
      let ts = this.重复检查();
      if (ts.length > 0) {
        this.$message({
          message: `${ts.join("、")} 重复！`,
          type: "error",
          center: true,
          duration: 2 * 1000,
        });
      }
    }, 50);
  }
  private handleClose() {
    this.uploadDialogVisible = false;
  }
  private 重复检查() {
    // if (项目名称) {
    //     if (this.tplDataLs.filter((it: any) => `${it.项目名称}${it.规格}${it.产地}`==项目名称).length > 1) {
    //         return [项目名称];
    //     }
    // }
    let ts = this.tplDataLs.map((it: any) => ({
      项目名称: it.项目名称,
      k: `${it.项目名称}${it.规格}${it.产地}`,
    }));
    let o: any = {};
    let ts2: Array<any> = [];

    ts.forEach((it: any) => {
      if (o[it.k] && o[it.k] == 1) {
        ts2.push(it.项目名称);
      }
      o[it.k] = (o[it.k] || 0) + 1;
    });

    return ts2;
  }
  public async 远程搜索项目(query: any) {
    this.项目Loading = true;
    const { data } = await autoName({ proType: this.editRow.类别, s: query });
    this.匹配项目s =
      data.map((it: any) => ({
        id: it.ID,
        label: it.名称,
        value: it,
        data: it,
      })) || [];
    this.项目Loading = false;
  }

  //隐藏基础项目
  public hideBasicObj: boolean = false;
  public 隐藏备选项目: boolean = false;
  public 本市标杆: boolean = false;
  public s: string = "";
  public filterTable($event: any) {
    let ts = this.tplDataLsCopy;

    if (this.hideBasicObj) {
      ts = ts.filter((it: any) => it.项目属性 !== "基础项目");
    }
    if (this.隐藏备选项目) {
      ts = ts.filter((it: any) => it.缺省);
    }

    if (this.s) {
      ts = ts.filter(
        (it: any) =>
          it.类别.indexOf(this.s) > -1 || it.项目名称.indexOf(this.s) > -1
      );
    }

    this.tplDataLs = ts;
  }
  public 项目属性s = [
    {
      lable: "无",
      value: "",
    },
    {
      lable: "基础项目",
      value: "基础项目",
    },
    {
      lable: "不判断",
      value: "不判断",
    },
  ];
  public 选择属性s = [
    {
      lable: "可选",
      value: "",
    },
    {
      lable: "必选",
      value: "必选",
    },
  ];

  public 模板名称: string = "";
  private created() {
    this.tplid = <string>this.$route.query.tid;
    this.模板名称 = <string>this.$route.query.tn;
    this.中医性质();
    this.loadTplDetail(this.tplid);
    this.loadTplById(this.tplid);
  }

  /**
   * 插入类别
   * @param row
   * @param index
   * @param cmd
   */
  public dropdownInsertType_itemClick(row: any, index: number, cmd: string) {
    if (cmd.startsWith("insertType")) {
      this.$prompt("请输入类别", "输入框", {
        inputPlaceholder: "如：药品、检验、检查、治疗、手术、耗材等",
      }).then((p: any) => {
        if (p.value) {
          this.dropdown_itemClick(row, index, cmd, p.value);
        }
      });
    }
  }
  public dropdown_itemClick(
    row: any,
    index: number,
    cmd: string,
    catory: string = ""
  ) {
    if (cmd == "remove") {
      this.tplDataLs.splice(index, 1);
      this.tplDataLsCopy.splice(index, 1);
    }

    if (cmd.startsWith("insert")) {
      let i = 1;
      if (cmd.endsWith("UP")) i = 0;
      index = index + i;
      index = index < 0 ? 0 : index;
      let o = {
        类别: catory || row.类别,
        缺省: false,
        单价: null,
        数量: null,
        模板费用: row.模板费用,
        标杆费用: row.标杆费用,
        本市标杆: row.本市标杆,
        本院标杆: row.本院标杆,
        模板费用占比: row.模板费用占比,
        费用结构情况: `${row.模板费用}/${
          this.本市标杆 ? row.本市标杆 : row.本院标杆
        }`,
      };
      console.log("insert", index);
      this.tplDataLs.splice(index, 0, o);
      this.tplDataLsCopy.splice(index, 0, o);
    }
  }

  public summary(param: any) {
    const { columns, data } = param;
    let sums: any = [];
    columns.forEach((c: any, index: number) => {
      if (index == 0) sums[index] = "合计";
      else if (c.property == "模板费用") {
        let ts = data
          .filter((it: any) => it.单价 && it.数量)
          .map((it: any) => it.单价 * it.数量)
          .reduce((a: number, b: number) => a + b, 0);
        sums[index] = (ts || 0).toFixed(2);
      }
    });
    this.tplLoading = false;
    return sums;
  }

  public 模板费用占比fmt(row: any, column: any) {
    let total = this.tplDataLs
      .filter((it: any) => it.金额)
      .map((it: any) => it.金额)
      .reduce((a: number, b: number) => a + b, 0);

    let r = this.tplDataLs
      .filter((it: any) => it.类别 == row.类别 && it.金额)
      .map((it: any) => it.金额)
      .reduce((a: number, b: number) => a + b, 0);

    let v = 0;
    if (total > 0) {
      v = (r / total) * 100;
    }
    row[column.property] = v;
    return v.toFixed(2);
  }

  public 费用结构情况fmt(row: any, column: any, cellValue: any, index: number) {
    let 类别 = row.类别;
    let r = this.tplDataLs
      .filter((it: any) => it.类别 == 类别 && it.金额)
      .map((it: any) => it.金额)
      .reduce((a: number, b: number) => a + b, 0);

    row[column.property] = r;

    return r.toFixed(2);
  }

  public 计算费用fmt(row: any, column: any, cellValue: any, index: number) {
    let c = column.property;
    let v = 0;
    if (row.数量 && row.单价) {
      v = row.数量 * row.单价;
    }
    row[c] = v;

    if (v == 0) return "";

    return v.toFixed(2);
  }
  public objectSpanMethod(r: any) {
    const { row, column, rowIndex, columnIndex } = r;

    let cols = ["类别", "费用结构情况", "模板费用占比"];

    if (!cols.includes(column.property)) {
      return {
        rowspan: 1,
        colspan: 1,
      };
    }

    if (!this.tplDataLs[rowIndex]) {
      // 1列 1行
      return {
        rowspan: 1,
        colspan: 1,
      };
    }

    if (this.tplDataLs[rowIndex - 1]) {
      if (
        this.tplDataLs[rowIndex][column.property] ==
        this.tplDataLs[rowIndex - 1][column.property]
      ) {
        // 0列 0 行
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
    if (this.tplDataLs[rowIndex + 1]) {
      if (
        this.tplDataLs[rowIndex][column.property] ==
        this.tplDataLs[rowIndex + 1][column.property]
      ) {
        let conutRowSpan = 1;
        let countIndex = 1;
        var len = this.tplDataLs.length;
        // 往下遍历 重复的列有几个 合并几个
        for (var i = rowIndex; i <= len; i++) {
          // 遍历数组
          if (
            this.tplDataLs[rowIndex + countIndex] &&
            this.tplDataLs[rowIndex][column.property] ==
              this.tplDataLs[rowIndex + countIndex][column.property]
          ) {
            countIndex += 1;
            conutRowSpan += 1;
          } else {
            break;
          }
        }
        // 2列1行
        return {
          rowspan: conutRowSpan,
          colspan: 1,
        };
      }
    }
  }

  //table数据源
  public tplDataLs: Array<any> = [];
  //数据源副本
  public tplDataLsCopy: Array<any> = [];

  public tplLoading: boolean = true;

  public saveLoading: boolean = false;

  /**
   * 保存模板TplDrg权重
   */
  private async saveTplDrg() {
    let o: any = JSON.parse(JSON.stringify(this.大数据标杆));

    let d: any = await drgweightbyid({
      wid: this.tplItem.路径ID,
      code: o.分组编码,
    });
    let ts = d.data || [];
    //模板标杆
    d = ts.filter((it: any) => it.来源 == 3);
    if (d.length > 0) {
      d = d[0];
      ts.filter((it: any) => it.来源 != 3).forEach((it: any) => {
        it.默认 = false;
        it.审核人 = "";
        it.审核时间 = "";
        saveTplDrg(it);
      });
    }

    let drgObj: any = {};
    this.tplDataLs.forEach((it: any) => {
      drgObj[it.类别] = it.模板费用;
    });
    o.mdc专业 = o.MDC专业;
    o.mdc中文名称 = o.MDC中文名称;
    o.路径id = this.tplItem.路径ID;
    Object.keys(drgObj).forEach((k: string) => {
      o[`平均${k}费`] = drgObj[k];
      d[`标准${k}费`] = drgObj[k];
    });
    // d.标准总费用 = o.平均费用;
    // d.标准总费用 =
    //   (Number(o.平均其他费) || 0) +
    //   (Number(o.平均手术费) || 0) +
    //   (Number(o.平均检查费) || 0) +
    //   (Number(o.平均检验费) || 0) +
    //   (Number(o.平均治疗费) || 0) +
    //   (Number(o.平均耗材费) || 0) +
    //   (Number(o.平均药品费) || 0) +
    //   (Number(o.平均药品费) || 0) +
    //   (Number(o.平均费用) || 0);
    const totalNum = this.tplDataLs
      .filter((it: any) => it.单价 && it.数量)
      .map((it: any) => it.单价 * it.数量)
      .reduce((a: number, b: number) => a + b, 0)
      .toFixed(2);
    d.标准总费用 = totalNum;
    d.标准床日 = o.平均床日;
    o.来源 = 3;
    d.默认 = true;
    d.审核人 = UserModule.name;
    d.审核时间 = new Date();
    o.来自模板 = true;
    console.log(o, totalNum, "o数据---------------------------------------");
    await saveTplDrg(d);
  }
  //保存模板
  public async saveTpl() {
    this.saveLoading = true;
    let 选择属性Map: any = {
      "": 0,
      必选: 1,
      可选: 0,
    };
    let 路径ID: any = this.tplDataLs.filter((it: any) => !!it.路径ID);
    if (路径ID.length > 0) {
      路径ID = 路径ID[0].路径ID;
    } else 路径ID = 0;

    this.tplDataLs.forEach((it: any, index: number) => {
      it.版本ID = this.tplid;
      it.执行性质 = 选择属性Map[it.选择属性];
      it.路径ID = 路径ID;
      it.序号 = index + 1;
    });
    let ls = JSON.parse(JSON.stringify(this.tplDataLs));
    ls.forEach((it: any) => {
      if (it.单价) it.单价 = parseFloat(it.单价);
      it.模板分类费用占比 = it.模板费用占比;
      it.模板病例数 = this.模板病例数;
    });
    if (this.tplItem.是否审核) {
      this.tplItem.审核时间 = Format("yyyy-MM-dd hh:mm:ss", new Date());
    } else {
      this.tplItem.审核时间 = "";
    }
    let ts = this.重复检查();
    if (ts.length > 0) {
      this.$alert(`${ts.join("、")} 重复！`);
    }
    /**
         * 初始化要求：
        1）组号一样
        2）选择属性，同为必选，或者同为可选；

         */
    let ts3 = ls
      .map((it: any) => ({ 选择属性: it.选择属性 || "可选", 组号: it.组号 }))
      .filter((it: any) => it.组号)
      .map((it: any) => `${it.选择属性}_${it.组号}`);
    if (ts3.length > 0) {
      let oo: any = {};
      ts3.forEach((t: any) => {
        oo[t] = (oo[t] || 0) + 1;
      });
      if (Object.keys(oo).filter((k: string) => oo[k] == 1).length > 0) {
        this.$message("组号和选择属性必须统一！");
      }
    }

    let o = { tpl: this.tplItem, ls: ls };
    let m = await saveTpl({ json: JSON.stringify(o) });

    if (this.tplItem.是否审核) this.saveTplDrg();
    this.saveLoading = false;
    this.$message("操作成功！");

    await this.loadTplById(this.tplid);
    if (this.tplDataLs.filter((it: any) => it.特征对比结果).length > 0) {
      //
      this.$message({
        type: "error",
        message: "红色项目可能不符合该路径，请详细检查！",
        duration: 5 * 1000,
      });
    }
  }

  public tplItem: any = {};
  private async loadTplById(tplid: string) {
    const { data } = await GetTplById({ id: tplid });
    this.tplItem = (data || {}).tpl;
    this.loadDrgNames(this.tplItem.路径ID);
  }

  public drgNameLs: Array<any> = [];

  private async loadDrgNames(wid: any) {
    const { data } = await drgNames({ wid: wid });
    this.drgNameLs = data || [];
    let ts = this.drgNameLs.filter(
      (it: any) => it.分组编码 == this.tplItem.分组编码
    );

    if (ts.length == 0 && this.drgNameLs.length > 0) {
      let t = this.tplItem.路径版本;
      if (t) {
        t = t.split("-")[0];
      }
      //先找5、9的
      let ts2 = this.drgNameLs.filter((it: any) => {
        return it.分组编码 == t + "5" || it.分组编码 == t + "9";
      });
      if (ts2.length == 0) {
        ts2 = this.drgNameLs.filter((it: any) => {
          return it.分组编码.startsWith(t);
        });
        if (ts2.length > 0) {
          this.tplItem.分组编码 = ts2[0].分组编码;
        } else {
          this.tplItem.分组编码 = this.drgNameLs[0].分组编码;
        }
      } else {
        this.tplItem.分组编码 = ts2[0].分组编码;
      }
    }
    this.loadDrgInfo(this.tplItem.分组编码);
  }

  private drgInfoes: Array<any> = [];
  private async loadDrgInfo(code: any) {
    const { data } = await drgInfo({ code: code });
    this.drgInfoes = data || [];
    this.大数据And历史标杆赋值();
  }

  private 大数据标杆: any = {};
  private 历史标杆: any = {};

  private 大数据And历史标杆赋值() {
    let ts = this.drgInfoes.filter((it: any) => it.版本 == "CHSDRG");
    if (ts.length > 0) {
      this.大数据标杆 = ts[0];
    }
    ts = this.drgInfoes.filter((it: any) => it.版本 == "HIS");
    if (ts.length > 0) {
      this.历史标杆 = ts[0];
    }
  }

  public tplitem_change(val: any) {
    this.loadDrgInfo(this.tplItem.分组编码);
    //this.大数据And历史标杆赋值();
  }
  private 是否中医性质: boolean = false;
  private async 中医性质() {
    const { data } = await cnHops({});
    this.是否中医性质 = data;
  }

  private 模板病例数: any = 0;

  private async loadTplDetail(tplid: string) {
    let loading = this.$loading({ text: "加载中...." });

    let d = await tplDetail({ tplid: tplid });
    let data = d.data || [];
    if (data.length == 0) {
      data = [];
    }
    let o: any = {};

    data.forEach((el: any, i: number) => {
      el.缺省 = el.数量 * el.单价 > 0.0;
      o[el.类别] = o[el.类别] || [];
      o[el.类别].push(el);
    });
    this.tplDataLs = data;

    if (this.tplDataLs.length > 0) {
      this.模板病例数 = this.tplDataLs[0].模板病例数 || 0;
    }
    this.tplDataLsCopy = JSON.parse(JSON.stringify(data));
    loading.close();
  }
}
</script>

<style lang="scss">
.el-table .cell {
  white-space: pre-line !important;
}

.el-row {
  padding: 5px;
}

.drgItem span + span {
  margin-left: 5px;
}

.el-descriptions__title {
  color: blue;
}

.menuDiv {
  display: none;
  position: absolute;

  .menuUl {
    height: auto;
    width: auto;
    font-size: 14px;
    text-align: left;
    border-radius: 3px;
    border: none;
    background-color: #c4c4c4;
    color: #fff;
    list-style: none;
    padding: 0 10px;

    li {
      width: 140px;
      height: 35px;
      line-height: 35px;
      cursor: pointer;
      border-bottom: 1px solid rgba(255, 255, 255, 0.47);

      &:hover {
        // background-color: rgb(26, 117, 158);
        color: rgb(54, 138, 175);
      }
    }
  }
}
</style>
